package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //线程池
    //TODO 企业中严禁用Executors创建线程池，而是自定义配置。
    private static final ExecutorService CACHE_REBUILDER_EXECUTOR = Executors.newFixedThreadPool(10);

    //加锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void delLock(String key) {
        stringRedisTemplate.delete(key);
    }

    //设置过期时间
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    //设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //解决缓存穿透的问题(总是发起一个不存在的值去请求，导致直接总是查数据库 比如 id = 0)
    public <R, ID> R queryWithPassThrough(String KeyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = KeyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        R r = dbFallBack.apply(id);
        if (r == null) {
            //如果数据库也查不到 那么redis存空值进去
            //空值策略
            this.set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //如果存在就写进redis
        this.set(key, r, time, unit);
        return r;
    }

    //逻辑过期解决缓存击穿问题（热点key失效了 在高并发的情况下 牺牲一部分一致性换取性能）
    //先让数据预热 然后测试的过程中过了10s 数据逻辑过期了 ，这个时候就会新开一条线程去重建缓存 其余的请求就会返回旧数据 直到缓存重构完成就能得到更新后的数据
    public <R, ID> R queryWithLogicalExpire(String KeyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit unit) {
        String key = KeyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);//json里面存的是RedisData数据包含data和expire过期时间
        if (StrUtil.isBlank(json)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //数据没有过期
            return r;
        }
        //数据已经过期 需要重新开一条线程去重建缓存
        //获取锁
        String LockKey = LOCK_SHOP_KEY + id;
        boolean flag = tryLock(LockKey);
        if (flag) {
            //成功拿到锁
            //开始开线程重构建热点缓存
            CACHE_REBUILDER_EXECUTOR.submit(() -> {
                try {
                    //查数据库
                    R r1 = dbFallBack.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //TODO 增加 “唯一标识 + Lua 释放”，彻底规避误释放风险
                    delLock(LockKey);
                }
            });
        }
        return r;
    }
}
